package com.horsecoder.im.common.protocol.convert;

import com.google.gson.Gson;
import com.horsecoder.im.common.protocol.codec.GsonSingleton;
import com.horsecoder.im.common.protocol.context.chain.response.Response;
import com.horsecoder.im.common.protocol.context.http.FullResponseContext;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

import java.nio.charset.StandardCharsets;

/**
 * Author: Zhu yuhan
 * Email: zhuyuhan2333@qq.com
 * Date: 2022/3/16 11:23 上午
 **/
public class ResponseConverter implements Converter<Response, FullResponseContext> {

    @Override
    public FullResponseContext convert(Response response) {
        Gson gson = GsonSingleton.gson();
        ByteBuf byteBuf = Unpooled.buffer();
        byteBuf.writeBytes(gson.toJson(response).getBytes(StandardCharsets.UTF_8));
        FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
        return new FullResponseContext(null, fullHttpResponse);
    }
}
